package api;



import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.type.GSet;
import indi.zjh.dp.verify.CharNotEmptyRule;
import indi.zjh.dp.verify.Check;
import indi.zjh.dp.verify.StringSetRule;
import log.Label;
import log.Log;

public class WriteLogApi extends Api {

	private static int MAX_LABEL_COUNT = 32; // 最大的标签数
	
	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = null;
		try
		{
			// 获取标签
			String[] labels = new String[MAX_LABEL_COUNT];
			int len = 0;
			for(int i = 0; i < MAX_LABEL_COUNT; ++i)
			{
				String label = ctx.getRequestParamValue("label"+i).trim();
				if(label == null || label.isEmpty() || label.length() == 0)
				{
					break;
				}
				labels[len++] = label;
			}
			
			// 获取级别
			String levelstr = ctx.getRequestParamValue("level").trim().toLowerCase();
			Check.data(levelstr).desc("日志级别错误").rule(new StringSetRule(GSet.createStringSet().addString("debug").addString("info").addString("business").addString("warn").addString("error").addString("fatal")));
			// 获取内容
			String content = ctx.getRequestParamValue("content").trim();
			Check.data(content).desc("日志内容不为空").rule(new CharNotEmptyRule());
			
			int level = Log.LEVEL_DEBUG;
			if(levelstr.equals("debug"))
				level = Log.LEVEL_DEBUG;
			else if(levelstr.equals("info"))
				level = Log.LEVEL_INFO;
			else if(levelstr.equals("business"))
				level = Log.LEVEL_BUSINESS;
			else if(levelstr.equals("warn"))
				level = Log.LEVEL_WARN;
			else if(levelstr.equals("error"))
				level = Log.LEVEL_ERROR;
			else if(levelstr.equals("fatal"))
				level = Log.LEVEL_FATAL;
			
			session = Configuration.getSessionFactory().createSession();
			
			Log log = new Log();
			log.setLevel(level);
			log.setContent(content);
			
			session.save(log);
			
			Query<Label> queryLabel = new Query<Label>(session);
			for(int i = 0; i < len; ++i)
			{
				Label label = null;
				Result<Label> result = queryLabel.find(Label.class, "`name` = '"+labels[i]+"'").result();
				if(result.count() == 0)
				{
					label = new Label();
					label.setName(labels[i]);
					session.save(label);
				}
				else
				{
					label = result.iterator().next();
				}
				
				label.getLogs().add(log);
				session.save(label);
			}
			
			Label.addDateLabel(session, log);
			
			session.commit();
			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			if(session != null)
			{
				session.rollback();
			}
			ctx.writeResponse("FAIL");
		}
		finally 
		{
			if(session != null)
			{
				session.close();
			}
		}
	}

}
